package org.magnerfuller.imtoolkit.server.connection.handler;

import java.util.Map;

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.*;

import org.magnerfuller.imtoolkit.server.connection.event.ConnectionEvent;
import org.magnerfuller.imtoolkit.server.session.medium.SessionDescription;
import org.magnerfuller.imtoolkit.server.session.medium.SessionMedium;
import org.magnerfuller.imtoolkit.server.session.medium.XMPPIMSessionMedium;

public class XMPPConnectionHandler extends ConnectionHandler implements PacketListener {
  
  private XMPPConnection connection;  // XMPP connection to Jabber server

  public static final String moduleName = "xmpp";
  
  public XMPPConnectionHandler() {  
    super();
    
  }
  
  public void initialize(Map<String, String> params) throws Exception {
    connection = new XMPPConnection(params.get("server"));
    connection.login(params.get("username"), params.get("password"));
  }

  public void run() {
    connection.addPacketListener(this, null);
  }
  
  public void processPacket(Packet packet) {
    if(packet instanceof Message) {
      Message message = (Message)packet;
      System.err.println("XMPPConnectionHandler::processPacket received packet!");
      if(connection.getChatManager().getThreadChat(message.getThread()) == null) {
        Chat newChat = connection.getChatManager().createChat(message.getFrom(), null);
        try {
          SessionMedium sessionMedium = new XMPPIMSessionMedium(newChat);
          SessionDescription sessionDesc = new SessionDescription(sessionMedium);
          fireConnectionEvent(new ConnectionEvent(this, sessionDesc));
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }

}
